package com.tpv.nfc_demo

import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.util.Locale
import kotlin.math.log

class MainActivity : AppCompatActivity() {


    val nfcAdapter by lazy { NfcAdapter.getDefaultAdapter(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }


    override fun onResume() {
        super.onResume()
        nfcAdapter.enableReaderMode(this, object : NfcAdapter.ReaderCallback {
            override fun onTagDiscovered(tag: Tag?) {
                //NdefRecord tnf=1 type=54 payload=02656E413834413633363834463445
                val ndef = Ndef.get(tag)
                val payload = ndef.cachedNdefMessage.records.first().payload
                val encoding = if (((payload.get(0).toInt() and 0xff) shr 7) > 0) "UTF-16" else "UTF-8"
                val encodingLength: Int = (payload.get(0).toInt() and 0x3f) + 1
                val length: Int = payload.size - encodingLength
                val readResult = String(payload, encodingLength, length, charset(encoding)).uppercase(Locale.getDefault())
                Log.i("hzb",readResult)
            }

        }, NfcAdapter.FLAG_READER_NFC_A  or
                NfcAdapter.FLAG_READER_NFC_B  or
                NfcAdapter.FLAG_READER_NFC_F or
                NfcAdapter.FLAG_READER_NFC_V or
                NfcAdapter.FLAG_READER_NFC_BARCODE,null)
    }


    fun ByteArrayToHexString(inarray: ByteArray): String {
        var i: Int
        var `in`: Int
        val hex = arrayOf(
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
            "B", "C", "D", "E", "F"
        )
        var out = ""


        var j = 0
        while (j < inarray.size) {
            `in` = inarray[j].toInt() and 0xff
            i = (`in` shr 4) and 0x0f
            out += hex[i]
            i = `in` and 0x0f
            out += hex[i]
            ++j
        }
        return out
    }

    override fun onPause() {
        super.onPause()
        nfcAdapter.disableReaderMode(this)
    }
}